package cn.tb.ymcc.service.impl;

import cn.tb.ymcc.domain.CourseMarket;
import cn.tb.ymcc.domain.CourseUserLearn;
import cn.tb.ymcc.dto.PayNotifyDto;
import cn.tb.ymcc.mapper.CourseUserLearnMapper;
import cn.tb.ymcc.service.ICourseMarketService;
import cn.tb.ymcc.service.ICourseUserLearnService;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author tangbo
 * @since 2022-07-21
 */
@Service
public class CourseUserLearnServiceImpl extends ServiceImpl<CourseUserLearnMapper, CourseUserLearn> implements ICourseUserLearnService {
    @Autowired
    private ICourseMarketService courseMarketService;

    /**
     * 保存用户的课程购买记录
     * 1.如果一个支付单购买了多个课程，那么应该保存多条购买记录
     * 2.课程观看的结束时间:
     *  开始时间 --现在
     *  结束时间 --现在时刻 + courseMarket中的可看天数
     *  ---------------------------
     *  续费-- 第一次购买，录入一条记录-- 第二次购买， 看课程是否过期
     *  。如果过期直接覆盖
     *  。如果没有过期，追加可看天数
     *  。订单号存最近购买的那个订单号（把以前历史的订单号覆盖掉）
     * @param payNotifyDto
     */
    @Override
    public void saveUserLear(PayNotifyDto payNotifyDto) {
        Map<String,Object> map = JSONObject.parseObject(payNotifyDto.getExtParams(), Map.class);
        Integer userId = (Integer)map.get("userId");
        String[] courseIds = map.get("courseId").toString().split(",");
        for (String courseId : courseIds) {
            CourseMarket market = courseMarketService.selectById(Long.valueOf(courseId));
            //查询曾今是否已经有记录
            CourseUserLearn learnTmp = selectByCourseIdAndLoginId(Long.valueOf(courseId), Long.valueOf(userId));
            Date now = new Date();
            //查不到就说明之前没有买过，直接新增
            if(learnTmp==null){
                CourseUserLearn learn = new CourseUserLearn();
                learn.setLoginId(Long.valueOf(userId));
                learn.setStartTime(now);
                Date endTime = DateUtils.addDays(now, market.getValidDays());
                learn.setEndTime(endTime);
                learn.setState(CourseUserLearn.STATE_PAY);
                learn.setCourseId(Long.valueOf(courseId));
                learn.setCourseOrderNo(payNotifyDto.getOrderNo());
                learn.setCreateTime(now);
                insert(learn);
            }else {
                //续费，修改
                learnTmp.setCourseOrderNo(payNotifyDto.getOrderNo());
                //看结束时间是否小于当前时间,过期了
                if(learnTmp.getEndTime().before(now)){
                    //如果过期直接覆盖
                    learnTmp.setLoginId(Long.valueOf(userId));
                    learnTmp.setStartTime(now);
                    Date endTime = DateUtils.addDays(now, market.getValidDays());
                    learnTmp.setEndTime(endTime);
                    learnTmp.setState(CourseUserLearn.STATE_PAY);
                    learnTmp.setCourseId(Long.valueOf(courseId));
                    learnTmp.setCreateTime(now);
            }else {
                    //如果没有过期，追加可看天数
                    Date endTime = DateUtils.addDays(learnTmp.getEndTime(), market.getValidDays());
                    learnTmp.setEndTime(endTime);
            }
            updateById(learnTmp);
            }
        }
    }

    private CourseUserLearn selectByCourseIdAndLoginId(Long courseId, Long loginId) {
        Wrapper<CourseUserLearn> wrapper = new EntityWrapper<>();
        wrapper.eq("course_id",courseId);
        wrapper.eq("login_id",loginId);
        return selectOne(wrapper);
    }
}
